package com.auth.config;

import com.auth.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] http_ignore_path = {"/v2/**","/swagger-resources","/webjars/**","/favicon.ico","/doc.html","/log/*","/admin/system/index/login/"};

    @Autowired
    @Lazy
    private UserService userService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }

    //密码模式才需要配置,认证管理器
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();

        http.authorizeRequests()
                .antMatchers(http_ignore_path).permitAll()
                .anyRequest().permitAll();

        http.formLogin()
                .loginProcessingUrl("/www.baidu.com")
                .permitAll();
    }

    @Bean
    public AuthenticationSuccessHandler successHandler() {
        return (request, response, authentication) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("state", 200);
            map.put("message", "login ok");
            //将map对象转换为json格式字符串并写到客户端
            String json = new ObjectMapper().writeValueAsString(map);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(json);
            out.flush();
            out.close();
        };
    }

    @Bean
    public AuthenticationFailureHandler failureHandler() {
        return (request,response,authentication) -> {
            Map<String,Object> map = new HashMap<>();
            map.put("state",500);
            map.put("message","login failure");
            //将map对象转换为json格式字符串并写到客户端
            String json = new ObjectMapper().writeValueAsString(map);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(json);
            out.flush();
            out.close();
        };
    }

    /*@Bean
    public org.springframework.security.core.userdetails.UserDetailsService userDetailsService() {
        return s -> {
            if ("admin".equals(s) || "user".equals(s)) {
                return new UserDetails(s, passwordEncoder().encode(s), s);
            }
            return null;
        };
    }*/
}